﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ExtendPropertyLib.WPF;
using MahApps.Metro;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.DragDrop;
using ExORMDesginer.Models;
using System.Collections;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using ExORMDesginer.Plugin;
using System.Windows.Media.Animation;

namespace ExORMDesginer
{
    /// <summary>
    /// Interaction logic for MainView.xaml
    /// </summary>

    public partial class MainView : MahApps.Metro.Controls.MetroWindow,IMainView
    {
        public MainView()
        {

            Windows8Palette.Palette.MainColor = (Color)ColorConverter.ConvertFromString("#FF1D1C1C");
            Windows8Palette.Palette.AccentColor = (Color)ColorConverter.ConvertFromString("#FF9731FF");
            Windows8Palette.Palette.BasicColor = (Color)ColorConverter.ConvertFromString("#FF6D11D4");
            Windows8Palette.Palette.StrongColor = Colors.Gray;
            Windows8Palette.Palette.MarkerColor = Colors.LightGray;
            Windows8Palette.Palette.ValidationColor = Colors.Red;
            StyleManager.ApplicationTheme = new Telerik.Windows.Controls.Windows8Theme();
            InitializeComponent();

            RadDragAndDropManager.AddDragInfoHandler(radTreeView1, OnDrapInfo);
          
            radTreeView1.AddHandler(RadDragAndDropManager.DropQueryEvent, new EventHandler<DragDropQueryEventArgs>(OnDropQuery), true);
            radTreeView1.AddHandler(RadDragAndDropManager.DropInfoEvent, new EventHandler<DragDropEventArgs>(OnDropInfo), true);
            radTreeView1.Selected += new EventHandler<Telerik.Windows.RadRoutedEventArgs>(radTreeView1_Selected);
            radTreeView1.ItemDoubleClick += new EventHandler<Telerik.Windows.RadRoutedEventArgs>(radTreeView1_ItemDoubleClick);
            width = new GridLength(220, GridUnitType.Pixel);
        }

        void radTreeView1_ItemDoubleClick(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            var radItem = e.OriginalSource as RadTreeViewItem;
            var info = radItem.Item as DbEntity;
            if (info != null)
            {
                var vm = this.DataContext as MainViewModel;
                vm.OnEntityNodeSelected(info);
            }
        }

        async void radTreeView1_Selected(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            var radItem = e.OriginalSource as RadTreeViewItem;
            var info = radItem.Item as FolderInfo;
            if (info != null)
            {
                var vm = this.DataContext as MainViewModel;
                vm.OnNoteClick(info);

            }
        }




        private bool toMinsize = false;
        GridLength width;
        public void ShowExplorer()
        {
            var grid = this.FindName("LeftBar") as Grid;

            GridLengthAnimation animation = new GridLengthAnimation();
            animation.From = new GridLength(this.toMinsize ? grid.ColumnDefinitions[0].Width.Value : 0.5, GridUnitType.Pixel);
            if (this.toMinsize)
            {
                width = grid.ColumnDefinitions[0].Width;
                animation.To = new GridLength(0.5, GridUnitType.Pixel);
            }
            else
                animation.To = width;

            animation.FillBehavior = FillBehavior.Stop;
            animation.Duration = new Duration(TimeSpan.FromSeconds(0.2));
            grid.ColumnDefinitions[0].Width = animation.To;
            grid.ColumnDefinitions[0].BeginAnimation(ColumnDefinition.WidthProperty, animation);

            this.toMinsize = !this.toMinsize;

            DoubleAnimation oLabelAngleAnimation = new DoubleAnimation();

            oLabelAngleAnimation.From = toMinsize ? 180 : 0;
            oLabelAngleAnimation.To = toMinsize ? 0 : 180;

            oLabelAngleAnimation.Duration
              = new Duration(new TimeSpan(0, 0, 0, 0, 500));

            RotateTransform oTransform
              = (RotateTransform)rotate.LayoutTransform;
            oTransform.BeginAnimation(RotateTransform.AngleProperty,
              oLabelAngleAnimation);


        }


       
        private void AppBarButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ShowExplorer();


          


        }


        FolderInfo sourceFolderInfo = null;
        /// <summary>
        /// 拖项目
        /// </summary>
        private void OnDrapInfo(object sender, DragDropEventArgs e)
        {
            RadTreeViewItem treeItem = e.Options.Source as RadTreeViewItem;

            if (treeItem.ParentItem != null && treeItem.ParentItem.Item != null)
            {
                sourceFolderInfo = treeItem.ParentItem.Item as FolderInfo;
            }


            if (e.Options.Status == DragStatus.DragComplete)
            {
                var currentEntitys = e.Options.Payload as Collection<object>;
                foreach (DbEntity currentEntity in currentEntitys)
                {
                    sourceFolderInfo.Items.Remove(currentEntity);
                    sourceFolderInfo.TableCollection.Remove(currentEntity);
                }
              

            }
        }

        /// <summary>
        /// 放下项目
        /// </summary>
        private void OnDropInfo(object sender,DragDropEventArgs e)
        {
            if (e.Options.Status == DragStatus.DropComplete)
            {
                RadTreeViewItem treeItem = e.Options.Destination as RadTreeViewItem;
                var curFolder = treeItem.Item as FolderInfo;
                var currentEntitys = e.Options.Payload as Collection<object>;
                foreach (DbEntity currentEntity in currentEntitys)
                {
                    curFolder.Items.Add(currentEntity);
                    curFolder.TableCollection.Add(currentEntity);
                }
            }
        }

        RadTreeViewItem sourceTreeViewItem;

        /// <summary>
        /// 拖动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDropQuery(object sender, DragDropQueryEventArgs e)
        {
            if (e.Options.Status == DragStatus.DropComplete)
            {
                sourceTreeViewItem = e.Options.Source as RadTreeViewItem;
            }


            RadTreeViewItem destinationItem = e.Options.Destination as RadTreeViewItem;

            object source = this.GetItemFromPayload<object>(e.Options.Payload);
            object target = destinationItem != null ? destinationItem.Item : null;
            DropPosition position = destinationItem != null ? destinationItem.DropPosition : DropPosition.Inside;

            if (source != null && target != null)
            {
                FolderInfo sourceGroup = source as FolderInfo;
                FolderInfo targetGroup = target as FolderInfo;
                DbEntity sourcePerson = source as DbEntity;
                DbEntity targetPerson = target as DbEntity;

          



                if (sourceGroup != null)
                {
                    e.QueryResult = false;
                    return;
                }

                if (sourceGroup == null)
                {
                    sourceTreeViewItem = e.Options.Source as RadTreeViewItem;
                    sourceGroup = sourceTreeViewItem.ParentItem.Item as FolderInfo;
                }




                if (targetGroup != null && sourceGroup != null)
                {
                    if (targetGroup.InfoType != sourceGroup.InfoType)
                    {
                        e.QueryResult = false;
                        return;
                    }
                }


                if (sourcePerson != null)
                {
                    if (sourcePerson != null && targetPerson != null && object.ReferenceEquals(sourcePerson, targetPerson))
                    {
                        e.QueryResult = false;
                        return;
                    }

                    if (targetPerson != null && position == DropPosition.Inside)
                    {
                        // do not allow dropping inside person
                        e.QueryResult = false;
                        return;
                    }

                    if (position != DropPosition.Inside && targetPerson == null)
                    {
                        e.QueryResult = false;
                        return;
                    }
                }
            }
            else
            {
                e.QueryResult = false;
                return;
            }


            
         
           
            e.QueryResult = true;
        }

        private T GetItemFromPayload<T>(object payload)
        {
            IEnumerable draggedItems = payload as IEnumerable;
            if (draggedItems != null)
            {
                return draggedItems.OfType<T>().FirstOrDefault();
            }
            return default(T);
        }




        public bool SelectDesignerItem(string name)
        {
            return Desginer.DesignerCanvas.SelectDesignerItem(name);
        }

        private void RadContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            
            RadTreeViewItem item = radContextMenu.GetClickedElement<RadTreeViewItem>();
            if (item != null)
            {
                if (item.Item is FolderInfo)
                    radContextMenu.ItemsSource = folderMenuItems;
                else if (item.Item is DbEntity)
                    radContextMenu.ItemsSource = entityMenuItems;
            }
      
        }

        private ObservableCollection<RadMenuItem> folderMenuItems
        {
            get
            {
                ObservableCollection<RadMenuItem> items = new ObservableCollection<RadMenuItem>();
                RadMenuItem item = new RadMenuItem();
                item.Header = "创建目录";
                var vm = this.DataContext as MainViewModel;
                RadTreeViewItem treeViewItem = radContextMenu.GetClickedElement<RadTreeViewItem>();
                item.Click += (s, e) => { vm.CreateFolder((FolderInfo)treeViewItem.Item); };
                RadMenuItem item1 = new RadMenuItem();
                item1.Header = "删除目录";
                items.Add(item);
                items.Add(item1);
                return items;


            }
        }

        private ObservableCollection<RadMenuItem> entityMenuItems
        {
            get
            {
                ObservableCollection<RadMenuItem> items = new ObservableCollection<RadMenuItem>();

                return null;


            }
        }

        private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)
        {
            var txtBox = e.OriginalSource as TextBox;
            txtBox.ScrollToEnd();
        }

    }
}
